const Schema = require('validate')
const { findAllDemoDao, addDemoDao, updateDemoDao, deleteDemoDao } = require('../dao/demoDao')
const { ValidationError } = require('../utils/errors')
const { formatResponse, handleDataPattern } = require('../utils/tool')

// 新增项目
module.exports.addDemoService = async function (newDemoInfo) {
  // 首先需要将 description 项目描述转换为字符串
  newDemoInfo.description = JSON.stringify(newDemoInfo.description)

  // 定义验证规则
  const demo = new Schema({
    name: {
      required: true,
      type: String,
    },
    url: {
      required: true,
      type: String,
    },
    github: {
      required: true,
      type: String,
    },
    description: {
      required: true,
      type: String,
    },
    order: {
      required: true,
      type: Number,
    },
    thumb: {
      required: true,
      type: String,
    },
  })

  // 进行数据验证
  const validateResult = demo.validate(newDemoInfo)
  if (validateResult.length == 0) {
    const data = await addDemoDao(newDemoInfo)
    return formatResponse(0, '', [data])
  } else {
    throw new ValidationError('数据验证失败')
  }
}

// 查询所有项目
module.exports.findAllDemoService = async function () {
  const data = await findAllDemoDao()
  // const obj = handleDataPattern(data)
  // 接下来需要将项目描述还原成数组
  const newObj = data.map((item) => {
    const parsedDescription = JSON.parse(item.description)
    item = { ...item, description: parsedDescription }
    return item
  })
  return formatResponse(0, '', newObj)
}

// 修改项目
module.exports.updateDemoService = async function (id, newDemoInfo) {
  if (newDemoInfo.description) {
    newDemoInfo.description = JSON.stringify(newDemoInfo.description)
  }
  const data = await updateDemoDao(id, newDemoInfo)
  // 还原项目描述
  data.description = JSON.parse(data.description)
  return formatResponse(0, '', [data])
}

// 删除项目
module.exports.deleteDemoService = async function (id) {
  await deleteDemoDao(id)
  return formatResponse(0, '', true)
}
